<!--
 * @Description: 
 * @Author: charles
 * @Date: 2021-12-19 10:11:07
 * @LastEditors: 方旬 14707008+fang-xun666@user.noreply.gitee.com
 * @LastEditTime: 2025-09-28 08:49:23
-->
<template>
  <div class="student-edit-page" style="padding: 20px;">
    <h3 style="margin-bottom: 20px;">学生信息编辑页</h3>

    <div class="student-item" v-for="(student, index) in studentList" :key="index"
      style="border: 1px solid #eee; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
      <!-- 姓名编辑 -->
      <div style="margin-bottom: 15px; display: flex; align-items: center;">
        <span style="margin-right: 10px;">姓名：</span>
        <el-input v-model="student.name" placeholder="输入学生姓名" style="width: 200px;"></el-input>
      </div>

      <!-- 爱好编辑 -->
      <div style="margin-bottom: 15px;">
        <span style="margin-right: 10px;">爱好：</span>
        <el-button v-for="(hobby, hIndex) in hobbyList" :key="hIndex"
          :type="student.selectedHobbies.includes(hobby) ? 'primary' : ''" round @click="toggleHobby(index, hobby)"
          style="margin-right: 8px; margin-bottom: 8px;">
          {{ hobby }}
        </el-button>
      </div>

      <!-- 标签管理区域 -->
      <div style="margin-bottom: 15px;">
        <span style="margin-right: 10px;">标签：</span>
        <!-- 已添加的标签 -->
        <el-tag v-for="(tag, tagIndex) in student.tags" :key="tagIndex" closable @close="deleteTag(index, tagIndex)"
          style="margin-right: 8px; margin-bottom: 8px;">
          {{ tag }}
        </el-tag>

        <!-- 新增标签输入框 + 添加按钮 -->
        <div style="display: flex; align-items: center; margin-top: 10px;">
          <el-input v-model="student.newTag" placeholder="输入新标签内容" style="width: 200px; margin-right: 10px;"
            @keyup.enter="addTag(index)"></el-input>
          <el-button type="success" size="small" @click="addTag(index)">
            <i class="el-icon-plus" style="margin-left: 30px;">添加标签</i>
          </el-button>
        </div>
      </div>

      <!-- 功能按钮区 -->
      <div>
        <el-button icon="el-icon-search" circle @click="viewDetail(student)" style="margin-right: 8px;"></el-button>
        <el-button type="primary" icon="el-icon-edit" circle @click="editCurrentStudent(index)"
          style="margin-right: 8px;"></el-button>
        <el-button type="success" icon="el-icon-check" circle @click="saveStudent(index)"
          style="margin-right: 8px;"></el-button>
        <el-button type="info" icon="el-icon-message" circle style="margin-right: 8px;"></el-button>
        <el-button type="warning" icon="el-icon-star-off" circle style="margin-right: 8px;"></el-button>
        <el-button type="danger" icon="el-icon-delete" circle @click="deleteStudent(index)"></el-button>
      </div>
    </div>

    <!-- 新增：批量保存按钮（可选，用于统一保存所有修改） -->
    <el-button 
      type="primary" 
      @click="saveAllStudents"
      style="margin-top: 10px; margin-right: 10px;"
    >
      <i class="el-icon-save"></i> 批量保存所有信息
    </el-button>
    <el-button 
      type="default" 
      @click="addNewStudent"
      style="margin-top: 10px;"
    >
      <i class="el-icon-plus"></i> 添加新学生
    </el-button>
  </div>
</template>

<script>
export default {
  name: 'StudentEditPageWithPersistentTags',
  data() {
    return {
      studentList: [], // 初始为空，通过本地存储加载
      hobbyList: ['阅读', '绘画', '运动', '音乐', '手工', '摄影', '编程', '书法']
    };
  },
  // 页面初始化时，从localStorage加载数据
  mounted() {
    this.loadStudentData();
  },
  methods: {
    // 核心：从localStorage加载学生数据
    loadStudentData() {
      const savedData = localStorage.getItem('studentInfoData');
      if (savedData) {
        // 有保存的数据，直接加载
        this.studentList = JSON.parse(savedData);
      } else {
        // 无保存数据，初始化默认学生信息
        this.studentList = [
          { name: '栗佳琪', selectedHobbies: ['阅读', '绘画'], tags: ['学霸'], newTag: '' },
          { name: '刘程琳', selectedHobbies: ['运动', '音乐'], tags: ['开朗'], newTag: '' },
          { name: '苗馨媛', selectedHobbies: ['手工', '摄影'], tags: ['创意'], newTag: '' }
        ];
        // 初始化时自动保存默认数据到本地
        this.saveToLocalStorage();
      }
    },

    // 核心：将当前学生数据保存到localStorage
    saveToLocalStorage() {
      localStorage.setItem('studentInfoData', JSON.stringify(this.studentList));
    },

    // 原有：切换爱好
    toggleHobby(studentIndex, hobby) {
      const student = this.studentList[studentIndex];
      student.selectedHobbies.includes(hobby)
        ? student.selectedHobbies = student.selectedHobbies.filter(item => item !== hobby)
        : student.selectedHobbies.push(hobby);
    },

    // 原有：查看详情
    viewDetail(student) {
      const tagStr = student.tags.length ? student.tags.join('、') : '无标签';
      this.$message.info(`
        ${student.name} 详情：
        爱好：${student.selectedHobbies.join('、')}
        标签：${tagStr}
      `);
    },

    // 原有：编辑提示
    editCurrentStudent(index) {
      this.$message.info(`进入 ${this.studentList[index].name} 的编辑模式`);
    },

    // 优化：保存单个学生信息（同步到本地存储）
    saveStudent(index) {
      this.saveToLocalStorage();
      this.$message.success(`已保存 ${this.studentList[index].name} 的信息（刷新不丢失）`);
    },

    // 新增：批量保存所有学生信息
    saveAllStudents() {
      this.saveToLocalStorage();
      this.$message.success('已批量保存所有学生信息（刷新不丢失）');
    },

    // 优化：删除学生（同步到本地存储）
    deleteStudent(index) {
      this.studentList.splice(index, 1);
      this.saveToLocalStorage(); // 删除后立即保存
      this.$message.warning('已删除该学生信息（刷新不恢复）');
    },

    // 原有：添加新学生
    addNewStudent() {
      this.studentList.push({
        name: '',
        selectedHobbies: [],
        tags: [],
        newTag: ''
      });
      this.$message.success('已添加新学生编辑项，请输入信息');
    },

    // 优化：添加标签（无需实时保存，仅在点击“保存”时同步）
    addTag(studentIndex) {
      const student = this.studentList[studentIndex];
      const tagValue = student.newTag.trim();
      if (tagValue && !student.tags.includes(tagValue)) {
        student.tags.push(tagValue);
        student.newTag = '';
        this.$message.success('标签添加成功，点击“保存”后刷新不丢失');
      } else if (!tagValue) {
        this.$message.warning('请输入标签内容');
      } else {
        this.$message.warning('该标签已存在，无需重复添加');
      }
    },

    // 优化：删除标签（无需实时保存，仅在点击“保存”时同步）
    deleteTag(studentIndex, tagIndex) {
      this.studentList[studentIndex].tags.splice(tagIndex, 1);
      this.$message.info('标签已删除，点击“保存”后刷新不丢失');
    }
  }
};
</script>

<style scoped>
.student-edit-page {
  max-width: 1200px;
  margin: 0 auto;
  /* 粉紫色背景：rgba确保柔和不刺眼，0.3为透明度（0-1可调） */
  background-color: rgba(236, 192, 255, 0.3);
  /* 让背景铺满整个视口高度，避免内容少的时候背景断层 */
  min-height: 100vh;
}
</style>